package com.hmall.order.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserCliet;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserHolder;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private UserCliet userCliet;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private IOrderLogisticsService orderLogisticsService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Override
    @GlobalTransactional
    public Long createOrder(RequestParams requestParams) {
        Order order = new Order();
        Item item = itemClient.getById(requestParams.getItemId());
        long totalFee = item.getPrice() * requestParams.getNum();
        order.setPaymentType(requestParams.getPaymentType());
        order.setUserId(UserHolder.getUser());
        order.setStatus(1);
        order.setTotalFee(totalFee);
        this.save(order);

        OrderDetail detail = new OrderDetail();
        detail.setName(item.getName());
        detail.setSpec(item.getSpec());
        detail.setPrice(item.getPrice());
        detail.setNum(requestParams.getNum());
        detail.setItemId(item.getId());
        detail.setOrderId(order.getId());
        orderDetailService.save(detail);

        Long addressId = requestParams.getAddressId();
        Address address = userCliet.findAddressById(addressId);
        OrderLogistics logistics = new OrderLogistics();
        BeanUtils.copyProperties(address, logistics);
        logistics.setOrderId(order.getId());

        orderLogisticsService.save(logistics);

        return order.getId();
    }
}
